import { ref } from "vue"

/**
 * 通用排序hook
 * @author Vic.xu
 * @since 2025-02-13
 * @param sortFieldMap 排序字段映射表，将 prop 映射为实际的排序字段
 * 使用：
    import { useTableSort } from "@@/composables/useTableSort"
    const { sortColumn, sortOrder, handleSortChange } = useTableSort({....})
    //查询参数：
    sortColumn: sortColumn.value,
    sortOrder: sortOrder.value,
    //监控变化
    watch([
      () => paginationData.currentPage,
      () => paginationData.pageSize,
      () => sortColumn.value,
      () => sortOrder.value],
      getTableData, { immediate: true })
      // table:
      @sort-change="handleSortChange"
      //column：
      sortable="custom"
 */
export function useTableSort(sortFieldMap: Record<string, string> = {}) {
  // 排序字段
  const sortColumn = ref<string>("")
  // 排序顺序
  const sortOrder = ref<"asc" | "desc" | "" | null>("")

  // 处理排序变化
  const handleSortChange = (data: { column: any, prop: string, order: string | null }) => {
    const { prop, order } = data
    if (order === "ascending") {
      sortColumn.value = sortFieldMap[prop] || prop // 使用映射表转换排序字段
      sortOrder.value = "asc"
    } else if (order === "descending") {
      sortColumn.value = sortFieldMap[prop] || prop // 使用映射表转换排序字段
      sortOrder.value = "desc"
    } else {
      sortColumn.value = ""
      sortOrder.value = ""
    }
  }

  return {
    sortColumn,
    sortOrder,
    handleSortChange
  }
}
